#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 14 11:32:35 2019

@author: jili
"""
## ---(Sun May 12 11:33:10 2019)---
from jili.data import db
from jili.trade.old.simpos import poslib as Poslib
from jili.calc import nhnl
import talib as ta
import pandas as pd
import math
from jili.calc import forwardwindows,backwindows
def app_out3sigma(i):
    up=i["upperband3"]
    down=i["lowerband3"]
    if i["high"]>=up:
        return 1
    elif i["low"]<=down:
        return 2
    else:
        return 0
def ischuitou(k):
    if k["close"]>=k["open"]:#red
        up=k["high"]-k["close"]
        down=k["open"]-k["low"]
        body=k["close"]-k["open"]
        if up>down:
            return 0,1,up/body,body/down
        else:
            return 1, 1, down / body, body / up
    else:
        up = k["high"] - k["open"]
        down = k["close"] - k["low"]
        body = k["open"] - k["close"]
        if up>down:
            return 0,0,up/body,body/down
        else:
            return 1, 0, down / body, body / up
def check_out3sigma(i,bais=0.05,feild=""):
    if feild=="":
        up=i["upperband3"]
        down=i["lowerband3"]
    else:
        up=i["premiddleband"]+3*i["presigma"]
        down=i["premiddleband"]-3*i["presigma"]
    if (i["high"]+bais*i["presigma"])>=up:
        return 1
    elif (i["low"]-bais*i["presigma"])<=down:
        return 2
    else:
        return 0
def app_close_on_sigma(i):
    up=i["upperband3"]
    down=i["lowerband3"]
    if i["close"]>=up:
        return 0
    elif i["close"]>=i["upperband2"] and i["close"]<i["upperband3"]:
        return 1
    elif i["close"]>=i["upperband1"] and i["close"]<i["upperband2"]:
        if i["close"]+i["sigma"]*0.08>=i["upperband2"]:
            return 1
        else:
            return 2
    elif i["close"]>=i["middleband"] and i["close"]<i["upperband1"]:
        return 3
    elif i["close"]>=i["lowerband1"] and i["close"]<i["middleband"]:
        return 4
    elif i["close"]>=i["lowerband2"] and i["close"]<i["lowerband1"]:
        if i["close"]-i["sigma"]*0.08<=i["lowerband2"]:
            return 6
        else:
            return 5
    elif i["close"]>i["lowerband3"] and i["close"]<i["upperband2"]:
        return 6
    elif i["close"]<=down:
        return 7

def app_high_on_sigma(i):
    up=i["upperband3"]
    down=i["lowerband3"]
    if i["high"]>=up:
        return 0
    elif i["high"]>=i["upperband2"] and i["high"]<i["upperband3"]:
        return 1
    elif i["high"]>=i["upperband1"] and i["high"]<i["upperband2"]:
        return 2
    elif i["high"]>=i["middleband"] and i["high"]<i["upperband1"]:
        return 3
    elif i["high"]>=i["lowerband1"] and i["high"]<i["middleband"]:
        return 4
    elif i["high"]>=i["lowerband2"] and i["high"]<i["lowerband1"]:
        return 5
    elif i["high"]>i["lowerband3"] and i["high"]<i["upperband2"]:
        return 6
    elif i["high"]<=down:
        return 7

def app_open_on_sigma(i):
    up=i["upperband3"]
    down=i["lowerband3"]
    if i["open"]>=up:
        return 0
    elif i["open"]>=i["upperband2"] and i["open"]<i["upperband3"]:
        return 1
    elif i["open"]>=i["upperband1"] and i["open"]<i["upperband2"]:
        return 2
    elif i["open"]>=i["middleband"] and i["open"]<i["upperband1"]:
        return 3
    elif i["open"]>=i["lowerband1"] and i["open"]<i["middleband"]:
        return 4
    elif i["open"]>=i["lowerband2"] and i["open"]<i["lowerband1"]:
        return 5
    elif i["open"]>i["lowerband3"] and i["open"]<i["upperband2"]:
        return 6
    elif i["open"]<=down:
        return 7

def app_low_on_sigma(i):
    up=i["upperband3"]
    down=i["lowerband3"]
    if i["low"]>=up:
        return 0
    elif i["low"]>=i["upperband2"] and i["low"]<i["upperband3"]:
        return 1
    elif i["low"]>=i["upperband1"] and i["low"]<i["upperband2"]:
        return 2
    elif i["low"]>=i["middleband"] and i["low"]<i["upperband1"]:
        return 3
    elif i["low"]>=i["lowerband1"] and i["low"]<i["middleband"]:
        return 4
    elif i["low"]>=i["lowerband2"] and i["low"]<i["lowerband1"]:
        return 5
    elif i["low"]>i["lowerband3"] and i["low"]<i["upperband2"]:
        return 6
    elif i["low"]<=down:
        return 7
def app_bar_on_sigma(i):
    up=i["upperband3"]
    down=i["lowerband3"]
    if i["barprice"]>=up:
        return 0
    elif i["barprice"]>=i["upperband2"] and i["barprice"]<i["upperband3"]:
        return 1
    elif i["barprice"]>=i["upperband1"] and i["barprice"]<i["upperband2"]:
        return 2
    elif i["barprice"]>=i["middleband"] and i["barprice"]<i["upperband1"]:
        return 3
    elif i["barprice"]>=i["lowerband1"] and i["barprice"]<i["middleband"]:
        return 4
    elif i["barprice"]>=i["lowerband2"] and i["barprice"]<i["lowerband1"]:
        return 5
    elif i["barprice"]>i["lowerband3"] and i["barprice"]<i["upperband2"]:
        return 6
    elif i["barprice"]<=down:
        return 7
def app_sigma_angle2_lable(i):
    #sigma_angle2_lable=""
    if i["sigma_angle2"]>=30:
        return "发散"
    elif i["sigma_angle2"]<=-30:
        return "收敛"
    elif i["sigma_angle2"]>-30 and i["sigma_angle2"]<30:
        return "持平"
def app_midband_angle_lable(i):
    if i["midband_angle"]>30:
        return "up"
    elif i["midband_angle"]<-30:
        return "down"
    elif i["midband_angle"]>-30 and i["midband_angle"]<30:
        return "ping"
def app_sigma_rate_lable(i):
    if i["sigma_rate"]>5:
        return "超高"
    elif i["sigma_rate"]>3.457 and i["sigma_rate"]<=5:
        return "高"
    elif i["sigma_rate"]>2.1159 and i["sigma_rate"]<=3.457:
        return "中"
    elif i["sigma_rate"]>1.342 and i["sigma_rate"]<=2.1159:
        return "低"
    elif i["sigma_rate"]>1 and i["sigma_rate"]<=1.342:
        return "超低"
    elif i["sigma_rate"]>0.618 and i["sigma_rate"]<=1:
        return "微"
    elif i["sigma_rate"]<=0.618:
        return "平"
def app_sigma_rate_lable0(i):
    if i["sigma_angle"]>=30:
        if i["sigma_rate"]>3:
            return "发散-宽幅"
        elif i["sigma_rate"]>1.5 and i["sigma_rate"]<=3:
            return "发散-中幅"
        elif i["sigma_rate"]<=1.5:
            return "发散-窄幅"
    elif i["sigma_angle"]<=-30:
        if i["sigma_rate"]>3:
            return "收敛-宽幅"
        elif i["sigma_rate"]>1.5 and i["sigma_rate"]<=3:
            return "收敛-中幅"
        elif i["sigma_rate"]<=1.5:
            return "收敛-窄幅"
    elif i["sigma_angle"]>-30 and i["sigma_angle"]<30:
        if i["sigma_rate"]>2:
            return "盘整-宽幅"
        elif i["sigma_rate"]>0.9 and i["sigma_rate"]<=2:
            return "盘整-中幅"
        elif i["sigma_rate"]<=0.9:
            return "盘整-窄幅"
def get_analysis_scene(i):
    a1=""
    a2=""
    a3=""
    a4=""
    if i["sigma_angle"]>=30:
        a1="发散"
        if i["sigma_rate"]>5:
            a2="超宽幅"
        elif i["sigma_rate"]>3.457 and i["sigma_rate"]<=5:
            a2="宽幅"
        elif i["sigma_rate"]>2 and i["sigma_rate"]<=3.457:
            a2="中幅"
        elif i["sigma_rate"]>1 and i["sigma_rate"]<=2:
            a2="窄幅"
        elif i["sigma_rate"]<=1:
            a2="极窄"
    elif i["sigma_angle"]<=-30:
        a1="收敛"
        if i["sigma_rate"]>5:
            a2="超宽幅"
        elif i["sigma_rate"]>3.457 and i["sigma_rate"]<=5:
            a2="宽幅"
        elif i["sigma_rate"]>2 and i["sigma_rate"]<=3.457:
            a2="中幅"
        elif i["sigma_rate"]>1 and i["sigma_rate"]<=2:
            a2="窄幅"
        elif i["sigma_rate"]<=1:
            a2="极窄"
    elif i["sigma_angle"]>-30 and i["sigma_angle"]<30:
        a1="盘整"
        if i["sigma_rate"]>1:
            a2="宽幅"
        elif i["sigma_rate"]>0.618 and i["sigma_rate"]<=1:
            a2="中幅"
        elif i["sigma_rate"]<=0.618:
            a2="极窄"
    if i["midband_angle"]>=30:
        a3="升"
        if i["midband_angle"]>68:
            a4="强"
        elif i["midband_angle"]>=43 and i["midband_angle"]<=68:
            a4="中"
        elif i["midband_angle"]<43:
            a4="低"
    elif i["midband_angle"]<=-30:
        a3="降"
        if i["midband_angle"]<-68:
            a4="强"
        elif i["midband_angle"]<=-43 and i["midband_angle"]>=-68:
            a4="中"
        elif i["midband_angle"]>-43:
            a4="低"
    elif i["midband_angle"]>-30 and i["midband_angle"]<30:
        a3="平"
        if i["midband_angle"]>20:
            a4="微上"
        elif i["midband_angle"]>=-20 and i["midband_angle"]<=20:
            a4="中"
        elif i["midband_angle"]<-20:
            a4="微下"
    return a1,a2,a3,a4
def app_midband_trend_lable(i):
    alpha=[40,20,12,5]
    ret=""
    if i["midband_angle"]>=alpha[0]:
        ret= "升-强"
    elif i["midband_angle"]>=alpha[1] and i["midband_angle"]<alpha[0]:
        ret= "升-中"
    elif i["midband_angle"]>=alpha[2] and i["midband_angle"]<alpha[1]:
        ret= "升-弱"
    elif i["midband_angle"]>alpha[3] and i["midband_angle"]<alpha[2]: 
        ret= "平-上"
    elif i["midband_angle"]>=-alpha[3] and i["midband_angle"]<=alpha[3]:
        ret= "平-中"
    elif i["midband_angle"]>-alpha[2] and i["midband_angle"]<-alpha[3]:
        ret= "平-下"
    elif i["midband_angle"]>-alpha[1] and i["midband_angle"]<=-alpha[2]:
        ret= "降-弱"
    elif i["midband_angle"]>-alpha[0] and i["midband_angle"]<=-alpha[1]:
        ret= "降-中"
    elif i["midband_angle"]<=-alpha[0]:
        ret= "降-强"
    i["trend"]=ret
    return ret
def app_midband_trend(i):
    alpha=[40,20,12,5]
    ret=""
    if i["midband_angle"]>=alpha[0]:
        ret= 3#"升-强"
    elif i["midband_angle"]>=alpha[1] and i["midband_angle"]<alpha[0]:
        ret= 2#"升-中"
    elif i["midband_angle"]>=alpha[2] and i["midband_angle"]<alpha[1]:
        ret= 1#"升-弱"
    elif i["midband_angle"]>alpha[3] and i["midband_angle"]<alpha[2]: 
        ret= 0.5#"平-上"
    elif i["midband_angle"]>=-alpha[3] and i["midband_angle"]<=alpha[3]:
        ret= 0#"平-中"
    elif i["midband_angle"]>-alpha[2] and i["midband_angle"]<-alpha[3]:
        ret= -0.5#"平-下"
    elif i["midband_angle"]>-alpha[1] and i["midband_angle"]<=-alpha[2]:
        ret= -1#"降-弱"
    elif i["midband_angle"]>-alpha[0] and i["midband_angle"]<=-alpha[1]:
        ret= -2#"降-中"
    elif i["midband_angle"]<=-alpha[0]:
        ret= -3#"降-强"
    i["trend"]=ret
    return ret
def app_bar_sigmaarea_lable(i):
    if i["bar_sigmaarea"] <=1:
        return"超强势"
    elif i["bar_sigmaarea"] >1 and i["bar_sigmaarea"] <= 2:
        return"强势"
    elif i["bar_sigmaarea"] >2 and i["bar_sigmaarea"] <= 3:
        return"弱势"
    elif i["bar_sigmaarea"] >3 and i["bar_sigmaarea"] <= 4:
        return"微势"
    elif i["bar_sigmaarea"] >4 and i["bar_sigmaarea"] <=5:
        return"微势"
    elif i["bar_sigmaarea"] >5 and i["bar_sigmaarea"] <= 6:
        return"弱势"
    elif i["bar_sigmaarea"] > 6 and i["bar_sigmaarea"] < 7:
        return"强势"
    elif i["bar_sigmaarea"] >7 :
        return"超强势"
def app_bar_sigmaarea_lable0(i):
    if i["bar_sigmaarea"] <=1:
        return"上方-超强势区"
    elif i["bar_sigmaarea"] >1 and i["bar_sigmaarea"] <= 2:
        return"上方-强势区"
    elif i["bar_sigmaarea"] >2 and i["bar_sigmaarea"] <= 3:
        return"上方-弱势区"
    elif i["bar_sigmaarea"] >3 and i["bar_sigmaarea"] <= 4:
        return"上方-微势区"
    elif i["bar_sigmaarea"] >4 and i["bar_sigmaarea"] <=5:
        return"下方-微势区"
    elif i["bar_sigmaarea"] >5 and i["bar_sigmaarea"] <= 6:
        return"下方-弱势区"
    elif i["bar_sigmaarea"] > 6 and i["bar_sigmaarea"] < 7:
        return"下方-强势区"
    elif i["bar_sigmaarea"] >7 :
        return"下方-超强势区"
def app_barprice_lable(i):
    if i["barprice_slope"]<-45:
        return "强-跌"
    elif i["barprice_slope"]<=-21 and i["barprice_slope"]>=-45:
        return "跌"
    elif i["barprice_slope"]<=-10 and i["barprice_slope"]>-21:
        return "微-跌"
    elif i["barprice_slope"]<10 and i["barprice_slope"]>-10:
        return "平"
    elif i["barprice_slope"]<21 and i["barprice_slope"]>=10:
        return "微-涨"
    elif i["barprice_slope"]<=45 and i["barprice_slope"]>=21:
        return "涨"
    elif i["barprice_slope"]>45:
        return "强-涨"
def app_midband_angle(i):
    return math.degrees(math.atan(i["midd_r0"]*3))
def app_ma5_angle(i):
    return math.degrees(math.atan(i["ma5_r0"]))
def app_close_angle(i):
    return math.degrees(math.atan(i["close_r0"]))
def sigma3(a,n=16):
    a["upperband3"], a["middleband"], a["lowerband3"] = ta.BBANDS(a["close"],n,3,3)
    a["upperband2"], a["middleband"], a["lowerband2"] = ta.BBANDS(a["close"],n)
    a["upperband1"], a["middleband"], a["lowerband1"] = ta.BBANDS(a["close"],n,1,1)
    a["ma5"]=ta.SMA(a["close"],5)
    a["ma10"]=ta.SMA(a["close"],10)
    a["ma20"]=ta.SMA(a["close"],20)
    a["ma40"]=ta.SMA(a["close"],40)
    a["ma60"]=ta.SMA(a["close"],60)
    a["sigma"]=a["upperband1"]-a["middleband"]
    a["sigma_rate"]=a["sigma"]/a["middleband"]*100
    a["midd_r0"]=a["middleband"].pct_change()*100
    a["midband_angle"]=a.apply(app_midband_angle,axis=1)
    del a["midd_r0"]
    a["sigma_angle"]=ta.LINEARREG_ANGLE(a["sigma"], timeperiod=2)
    a["ma5_r0"]=a["ma5"].pct_change()*100
    a["ma5_angle"]=a.apply(app_ma5_angle,axis=1)
    del a["ma5_r0"]
    a["close_r0"]=a["close"].pct_change()*100
    a["close_angle"]=a.apply(app_close_angle,axis=1)
    del a["close_r0"]
    #a=k1d1.describe()
    
    a["bar_close_sigmaarea"]=a.apply(app_close_on_sigma,axis=1)
    a["bar_high_sigmaarea"]=a.apply(app_high_on_sigma,axis=1)
    a["bar_open_sigmaarea"]=a.apply(app_open_on_sigma,axis=1)
    a["bar_low_sigmaarea"]=a.apply(app_low_on_sigma,axis=1)
    a["barprice"]=((a["high"]+a["open"]+a["low"])+3*a["close"])/6
    a["barprice_sigmaarea"]=a.apply(app_bar_on_sigma,axis=1)
    a["bar_sigmaarea"]=((a["bar_high_sigmaarea"]+a["bar_open_sigmaarea"]+a["bar_low_sigmaarea"])+3*a["bar_close_sigmaarea"])/6
    a["out_3sigma"]=a.apply(app_out3sigma,axis=1)
    
    a["midband_trend"]=a.apply(app_midband_trend,axis=1)
    a["sigma_angle_lable"]=a.apply(app_sigma_rate_lable0,axis=1)
    a["midband_trend_lable"]=a.apply(app_midband_trend_lable,axis=1)
    a["scene"]=a["sigma_angle_lable"]+"_"+a["midband_trend_lable"]
    tacalc(a)
    #nhnl.
    return a
def tacalc(a):
    a["macd"], a["macd_signal"], a["macd_hist"] = ta.MACD(a["close"],12,26,9)
    a["kdj_k"], a["kdj_d"] = ta.STOCH(a["high"],a["low"],a["close"],9,3,0,3,0)
    a["kdj_j"]=3*a["kdj_k"]-2*a["kdj_d"]
    a["rsi"]=ta.RSI(a["close"],6)
    a["sar"]=ta.SAR(a["high"],a["low"])
    a["cci"] = ta.CCI(a["high"],a["low"],a["close"])
    a["obv"] = ta.OBV(a["close"],a["volume"])
    #a["mass"] = ta.MASS(a["close"],a["volume"])
    a["t3"]=ta.T3(a["close"])
    a["ad"]=ta.AD(a["high"],a["low"],a["close"],a["volume"])
def cha(data,f1,f2,f3="cha"):
    values=[]
    ispd=False
    if isinstance(data,dict):
        values=list(data.values())
    elif isinstance(data,list):
        values=data
    elif isinstance(data,pd.DataFrame):
        ispd=True
        values=data.to_dict("records")
    count=0
    for i in backwindows(values,2):
        n=len(i)
        if n>=2:
            if (i[0][f1]<i[0][f2]) and (i[1][f1]>=i[1][f2]):#jincha
                count=0
                i[1][f3]="jincha"
            elif (i[0][f1]>i[0][f2]) and (i[1][f1]<=i[1][f2]):#sicha
                count=0
                i[1][f3]="sicha"
            else:
                count=count+1
                b=i[0][f1]-i[0][f2]
                a=(i[1][f1]-i[1][f2])-b
                i[1][f3]=math.degrees(math.atan2(a,i[0][f1]))
    if ispd:
        data=pd.DataFrame(values)
    return data
def P(data,x,y):
    values=[]
    ispd=False
    if isinstance(data,dict):
        values=list(data.values())
    elif isinstance(data,list):
        values=data
    elif isinstance(data,pd.DataFrame):
        ispd=True
        values=data.to_dict("records")
    rst1=0
    rst2=0
    for i in values:
        isxx=Pcheck(i,x)
        isyy=Pcheck(i,y)
        if isxx:
            rst1=rst1+1
        if isxx and isyy:
            rst2=rst2+1
    if ispd:
        data=pd.DataFrame(values)
    if rst1==0:
        return 0,rst2,rst1
    else:
        return rst2/rst1,rst2,rst1
def Pcheck(i,x):
    if isinstance(x,dict):
        rst=True
        for k,v in x.items():
            if hasattr(v,'__call__'):
                if not v(i[k]):
                    rst=rst and False
            else:
                if i[k]!=v:
                    rst=rst and False
        return rst
    elif hasattr(x,'__call__'):
        return x(i)
    elif isinstance(x,list):
        rst=True
        for xx in x:
            if isinstance(xx,dict):
                rst1=True
                for k,v in xx.items():
                    if hasattr(v,'__call__'):
                        if not v(i[k]):
                            rst1=rst1 and False
                    else:
                        if i[k]!=v:
                            rst1=rst1 and False
                rst = rst and rst1
            elif hasattr(xx,'__call__'):
                rst = rst and  xx(i)
            else:
                rst = rst and  False
        return rst
    else:
        return False
def bs1(i):
    if i["out_3sigma"]==1:
        return "卖出"
    elif i["out_3sigma"]==2:
        return "买入"
    else:
        return ""
    
def bs2(i):
    if i["sigma_9angle"]>30 and i["middleband_9angle"]<-30 and i["sigma_rate"]<=1:
        return "卖出"
    elif i["sigma_9angle"]>30 and i["middleband_9angle"]>30 and i["sigma_rate"]<=1:
        return "买入"
    else:
        return ""
def get(obj):
    k1d1=db.getkline1d_adj("rb")
    sigma3(k1d1)
    return k1d1
def kline_bbands(a,name="Kline",t={}):
    from pyecharts.charts import Kline,Line,Grid,Bar,EffectScatter
    kline = Kline("RB")
    x = a["timekey"].apply(lambda x: str(x)[:10]).tolist()
    #k_plot_value = a.apply(lambda record: [record['open'], record['close'], record['low'], record['high']], axis=1).tolist()
    kline.add(
        "rb日K",
        x,
        a.loc[:,["open", "close", "low", "high"]].values.tolist(),
        mark_point=["max","min"],
        is_datazoom_show=True,
        datazoom_type="both",
        tooltip_axispointer_type="cross",
        tooltip_trigger="axis",
        datazoom_range=[94,100],
        datazoom_xaxis_index=[0,1]
    )
    line1 = Line()
    line1.add("upperband3", x, a["upperband3"].values.tolist(),is_symbol_show=False, is_smooth=False,tooltip_tragger="axis")
    line1.add("upperband2", x, a["upperband2"].values.tolist(),is_symbol_show=False, is_smooth=False,tooltip_tragger="axis")
    line1.add("upperband1", x, a["upperband1"].values.tolist(),is_symbol_show=False, is_smooth=False,tooltip_tragger="axis")
    line1.add("middleband", x, a["middleband"].values.tolist(), is_symbol_show=False, is_smooth=False,tooltip_tragger="axis")
    line1.add("lowerband1", x, a["lowerband1"].values.tolist(),is_symbol_show=False,  is_smooth=False,tooltip_tragger="axis")
    line1.add("lowerband2", x, a["lowerband2"].values.tolist(),is_symbol_show=False,  is_smooth=False,tooltip_tragger="axis")
    line1.add("lowerband3", x, a["lowerband3"].values.tolist(),is_symbol_show=False, is_smooth=False,tooltip_tragger="axis")

    kline.add(line1)
    
    if t:
        es1=EffectScatter()
        es1.add("buy",t["x"],t["y"],
            symbol_size=5,
            effect_scale=3,
            effect_period=3,
            symbol="arrow",
        )
        overlap1.add(es1)
    bar1=Bar()
    bar1.add("成交量",x,a["volume"].values.tolist(),is_legend_show=False,tooltip_tragger="axis")
    #line2 = Line()
    #line2.add("VMA5", x, a["VMA5"].values.tolist(),is_symbol_show=False, is_smooth=True,is_legend_show=False,tooltip_tragger="axis")
    #line2.add("VMA10", x, a["VMA10"].values.tolist(), is_symbol_show=False, is_smooth=True,is_legend_show=False,tooltip_tragger="axis")
    overlap2 = Overlap()
    overlap2.add(bar1)
    #overlap2.add(line2)
    grid = Grid(page_title=name,width=1900,height=1000)
    grid.add(overlap1, grid_bottom="20%")
    grid.add(overlap2, grid_top="80%")
    grid.render(name+".html") 
def case1(a,name="report",bais=0.05,feild=""):
    ispd=False
    if isinstance(a,pd.DataFrame):
        a=a.to_dict("index")
        ispd=True
    f=[]
    kline={}
    t=[]
    pos={"x":[],"y":[]}
    ret0={}
    ret={}
    ret["总机会"]=0
    ret["假机会"]=0
    ret["真机会"]=0
    ret["总数"]=len(a)
    ret["机会占比"]=0
    ret["查伪率"]=0
    ret["总盈亏"]=0
    ret["平均"]=0
    ret["可能问题"]=0
    ret["可能问题pl"]=0
    back=15
    forward=0
    for k,v in a.items():
        check=check_out3sigma(v,bais,feild)
        if check!=0:
            x=str(k)[:10]
            pos["x"].append(x)
            y=v["low"]-5
            pos["y"].append(y)
            if forward<=0:
                for i in f:
                    kline.update({k:i})
                forward=10
            tt={}
            tt["out_3sigma"]=check
            tt["timekey"]=k
            tt["pingjia"]=v["pingjia"]
            tt["sigma"]=v["sigma"]
            tt["sigma_rate"]=v["sigma_rate"]
            tt["midband_angle_lable"]=v["midband_angle_lable"]
            tt["upperband3"]=v["upperband3"]
            tt["lowerband3"]=v["lowerband3"]
            if v["out_3sigma"]==1:#卖出               
                tt["bs"]="卖出"
                tt["open"]=v["high"]-3
                tt["close"]=v["close"]-1
                tt["pl"]=tt["open"]-tt["close"]
                if tt["pl"]>0 and tt["upperband3"]<tt["close"]:
                    ret["可能问题"]=ret["可能问题"]+1
                    ret["可能问题pl"]=ret["可能问题pl"]+tt["pl"]
            else:
                tt["bs"]="买入"
                tt["open"]=v["low"]+3
                tt["close"]=v["close"]-1
                tt["pl"]=tt["close"]-tt["open"]
                if tt["pl"]>0 and tt["lowerband3"]>tt["close"]:
                    ret["可能问题"]=ret["可能问题"]+1
                    ret["可能问题pl"]=ret["可能问题pl"]+tt["pl"]
            tt["r"]=tt["pl"]/tt["open"]*100
            t.append(tt)
            ret["总机会"]=ret["总机会"]+1
            ret["总盈亏"]=ret["总盈亏"]+tt["pl"]
            if tt["pl"]>0:
                ret["真机会"]=ret["真机会"]+1
            else:
                ret["假机会"]=ret["假机会"]+1
        else:
            if forward>0:
                kline.update({k:v})
                forward=forward-1
        f.append(v)
        if len(f)>back:
            f.pop(0)
    ret["机会占比"]=ret["总机会"]/ret["总数"]
    ret["查伪率"]=ret["假机会"]/ret["总机会"]
    ret["问题占比"]=ret["可能问题"]/ret["真机会"]
    ret["净盈亏"]=ret["总盈亏"]-ret["可能问题pl"]
    ret["平均"]=ret["总盈亏"]/ret["总机会"]
    ret0["交易记录"]=t
    ret0["kline"]=kline
    ret0["pos"]=pos
    ret0["ret"]=ret
    if ispd:
        a=pd.DataFrame(a).T
    if name!="":
        kline0=pd.DataFrame(kline).T
        kline_bbands(kline0,name,pos)
    return ret0
class scene():
    def __init__(self):
        pass
class sigma():
    def __init__(self,alpha=[40,20,12,5]):
        self.history=[]
        self.pos=Poslib()
        self.hypothesis={}
        self.__scene=dict()
        self.alpha=alpha
        self.beta=[0.9]
    def app_midband_trend(self,i):
        ret=""
        if i["midband_angle"]>=self.alpha[0]:
            ret= 3#"升-强"
        elif i["midband_angle"]>=self.alpha[1] and i["midband_angle"]<self.alpha[0]:
            ret= 2#"升-中"
        elif i["midband_angle"]>=self.alpha[2] and i["midband_angle"]<self.alpha[1]:
            ret= 1#"升-弱"
        elif i["midband_angle"]>self.alpha[3] and i["midband_angle"]<self.alpha[2]: 
            ret= 0.5#"平-上"
        elif i["midband_angle"]>=-self.alpha[3] and i["midband_angle"]<=self.alpha[3]:
            ret= 0#"平-中"
        elif i["midband_angle"]>-self.alpha[2] and i["midband_angle"]<-self.alpha[3]:
            ret= -0.5#"平-下"
        elif i["midband_angle"]>-self.alpha[1] and i["midband_angle"]<=-self.alpha[2]:
            ret= -1#"降-弱"
        elif i["midband_angle"]>-self.alpha[0] and i["midband_angle"]<=-self.alpha[1]:
            ret= -2#"降-中"
        elif i["midband_angle"]<=-self.alpha[0]:
            ret= -3#"降-强"
        i["trend"]=ret
        return ret
    def analysis_scene(self,i):
        if self.history:
            t=self.history[-1]
            if t["sigma_angle"]>=30:
                self.sigma1(t,i)
            elif t["sigma_angle"]<=-30:
                self.sigma2(t,i)
            else:
                self.sigma0(t,i)
        else:
            self.app_midband_trend(i)
            i["time"]=1
        self.history.append(i)
    def sigma0(self,t,i):
        trendi=self.app_midband_trend(i)
        if t["sigma_angle"]<self.beta[0]:#开口逻辑
            if i["sigma_angle"]>30:#开口
                if trendi>=1:#up
                    self.pos.openbuy(i["timekey"],i["close"])
                    i["bs"]="buy_open:"+str(i["close"])
                    i["time"]=1
                    #i["kaikou"]="开口"
                elif trendi<=-1:#down
                    self.pos.opensell(i["timekey"],i["close"])
                    i["bs"]="sell_open:"+str(i["close"])
                    i["time"]=1
                else:#ping
                    i["time"]=t["time"]+1
            else:#继续收口盘整
                i["time"]=t["time"]+1
        else:#趋势不明
            i["time"]=t["time"]+1
    def sigma1(self,t,i):
        trendi=self.app_midband_trend(i)
        trendt=t["trend"]
        if trendt >=1:
            if i["sigma_angle"]<30:#拐点
                #i["bs"]="2sell_close:"+str(i["close"])
                if (trendt>=3) and (i["close"]<i["upperband2"]):#平买单
                    self.pos.closesell(i["timekey"],i["close"])
                    i["bs"]="sell_close:"+str(i["close"])
                    i["time"]=1
                
                else:
                    i["time"]=t["time"]+1
            else:
                if abs(trendt)>abs(trendi):#趋势减弱；验证判断
                    i["time"]=t["time"]+1
                else:#趋势延续计算趋势天数
                    i["time"]=t["time"]+1
        elif trendt <=-1:
            if i["sigma_angle"]<30:#拐点
                if trendt<=-3 and i["close"]>i["lowerband3"]:#平sell单
                    self.pos.closebuy(i["timekey"],i["close"])
                    i["bs"]="buy_close:"+str(i["close"])
                    i["time"]=1
                else:
                    i["time"]=t["time"]+1
            else:
                if abs(trendt)>abs(trendi):#趋势减弱；验证判断
                    i["time"]=t["time"]+1
                else:#趋势延续计算趋势天数
                    i["time"]=t["time"]+1
        else:
            i["time"]=t["time"]+1

    def sigma2(self,t,i):
        self.app_midband_trend(i)
        trendi=self.app_midband_trend(i)
        #trendt=t["trend"]
        if t["sigma_rate"]<self.beta[0]:#开口逻辑
            if i["sigma_angle"]>30:#开口
                if trendi>=1:#up
                    self.pos.openbuy(i["timekey"],i["close"])
                    i["bs"]="buy_open:"+str(i["close"])
                    i["time"]=1
                elif trendi<=-1:#down
                    self.pos.opensell(i["timekey"],i["close"])
                    i["bs"]="sell_open:"+str(i["close"])
                    i["time"]=1
                else:#ping
                    i["time"]=t["time"]+1
            else:#继续收口盘整
                i["time"]=t["time"]+1
        else:
            i["time"]=t["time"]+1
    def deal(self,a):
        ispd=False
        if isinstance(a,pd.DataFrame):
            a=a.to_dict("index")
            ispd=True
        for i in a.values():
            self.analysis_scene(i)
        if ispd:
            a=pd.DataFrame(a).T
def case2(a,name="report",bais=0.05,feild=""):
    ispd=False
    if isinstance(a,pd.DataFrame):
        a=a.to_dict("index")
        ispd=True
    f=[]
    kline={}
    t=[]
    pos={"x":[],"y":[]}
    ret0={}
    ret={}
    ret["总机会"]=0
    ret["假机会"]=0
    ret["真机会"]=0
    ret["总数"]=len(a)
    ret["机会占比"]=0
    ret["查伪率"]=0
    ret["总盈亏"]=0
    ret["平均"]=0
    history={}
    back=15
    forward=0
    for k,v in a.items():
        check=check_out3sigma(v,bais,feild)
        if check!=0:
            x=str(k)[:10]
            pos["x"].append(x)
            y=v["low"]-5
            pos["y"].append(y)
            if forward<=0:
                for i in f:
                    kline.update({k:i})
                forward=10
            tt={}
            tt["out_3sigma"]=check
            tt["timekey"]=k
            tt["pingjia"]=v["pingjia"]
            tt["sigma"]=v["sigma"]
            tt["sigma_rate"]=v["sigma_rate"]
            tt["midband_angle_lable"]=v["midband_angle_lable"]
            if v["out_3sigma"]==1:#卖出               
                tt["bs"]="卖出"
                tt["open"]=v["high"]-3
                tt["close"]=v["close"]-1
                tt["pl"]=tt["open"]-tt["close"]
            else:
                tt["bs"]="买入"
                tt["open"]=v["low"]+3
                tt["close"]=v["close"]-1
                tt["pl"]=tt["close"]-tt["open"]
            tt["r"]=tt["pl"]/tt["open"]*100
            t.append(tt)
            ret["总机会"]=ret["总机会"]+1
            ret["总盈亏"]=ret["总盈亏"]+tt["pl"]
            if tt["pl"]>0:
                ret["真机会"]=ret["真机会"]+1
            else:
                ret["假机会"]=ret["假机会"]+1
        else:
            if forward>0:
                kline.update({k:v})
                forward=forward-1
        f.append(v)
        if len(f)>back:
            f.pop(0)
    ret["机会占比"]=ret["总机会"]/ret["总数"]
    ret["查伪率"]=ret["假机会"]/ret["总机会"]
    ret["平均"]=ret["总盈亏"]/ret["总机会"]
    ret0["交易记录"]=t
    ret0["kline"]=kline
    ret0["pos"]=pos
    ret0["ret"]=ret
    if ispd:
        a=pd.DataFrame(a).T
    if name!="":
        kline0=pd.DataFrame(kline).T
        kline_bbands(kline0,name,pos)
    return ret0
def case3(a,name=""):
    ispd=False
    if isinstance(a,pd.DataFrame):
        a=a.to_dict("index")
        ispd=True
    f=[]
    kline={}
    t=[]
    pos={"x":[],"y":[]}
    ret0={}
    ret={}
    ret["总机会"]=0
    ret["假机会"]=0
    ret["真机会"]=0
    ret["总数"]=len(a)
    ret["机会占比"]=0
    ret["查伪率"]=0
    ret["总盈亏"]=0
    ret["平均"]=0
    back=0
    for k,v in a.items():
        check=check_out3sigma(v,bais,feild)
        if check!=0:
            x=str(k)[:10]
            pos["x"].append(x)
            y=v["low"]-5
            pos["y"].append(y)
            if back<=0:
                for i in f:
                    kline.update({k:i})
                back=10
            tt={}
            tt["out_3sigma"]=check
            tt["timekey"]=k
            tt["pingjia"]=v["pingjia"]
            tt["sigma"]=v["sigma"]
            tt["sigma_rate"]=v["sigma_rate"]
            tt["midband_angle_lable"]=v["midband_angle_lable"]
            if v["out_3sigma"]==1:#卖出               
                tt["bs"]="卖出"
                tt["open"]=v["high"]-3
                tt["close"]=v["close"]-1
                tt["pl"]=tt["open"]-tt["close"]
            else:
                tt["bs"]="买入"
                tt["open"]=v["low"]+3
                tt["close"]=v["close"]-1
                tt["pl"]=tt["close"]-tt["open"]
            tt["r"]=tt["pl"]/tt["open"]*100
            t.append(tt)
            ret["总机会"]=ret["总机会"]+1
            ret["总盈亏"]=ret["总盈亏"]+tt["pl"]
            if tt["pl"]>0:
                ret["真机会"]=ret["真机会"]+1
            else:
                ret["假机会"]=ret["假机会"]+1
        else:
            if back>0:
                kline.update({k:v})
                back=back-1
        f.append(v)
        if len(f)>15:
            f.pop(0)
    ret["机会占比"]=ret["总机会"]/ret["总数"]
    ret["查伪率"]=ret["假机会"]/ret["总机会"]
    ret["平均"]=ret["总盈亏"]/ret["总机会"]
    ret0["交易记录"]=t
    ret0["kline"]=kline
    ret0["pos"]=pos
    ret0["ret"]=ret
    if ispd:
        a=pd.DataFrame(a).T
    if name!="":
        kline0=pd.DataFrame(kline).T
        kline_bbands(kline0,name,pos)
    return ret0
#def selfta(i)